"use client";
import React from "react";
import { RegisterForm } from "@/components/register-form";
import { RegisterSchema } from "@/schemas";
import { Card } from "@/components/ui/card";

import { useRouter } from "next/navigation";
import bcrypt from "bcryptjs";
import * as z from "zod";
import { toast } from "sonner";
const RegisterPage = () => {
  console.log("register page");
  const router = useRouter();
  const onSubmit = async (values: z.infer<typeof RegisterSchema>) => {
    const hashedPassword = await bcrypt.hash(values.password, 10);
    const userdata = { ...values, password: hashedPassword };
    await fetch("/api/user/create", {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(userdata),
    })
      .then(async (resp) => {
        if (resp.ok) {
          toast.info("创建账户成功");
          router.push("/auth/login");
        } else {
          throw await resp.json();
        }
      })
      .catch((error) => {
        toast.error(error.message);
      });
  };

  return (
    <section>
      <Card className="gap-5">
        <RegisterForm handleSubmit={onSubmit} />
      </Card>
    </section>
  );
};

export default RegisterPage;
